package com.china08.yxyapi.api.home.activity.healthcompetition.huodongtongji;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.mg.huodong.healthcompetition.YxyCompetitionStudent;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.mg.huodong.YxyCompetitionStudentRepository;

/**
 * 健康知识竞赛 该学校总参与人数 参与率 平均分
 * 
 * @author zd.Jin
 *
 *
 */
@CrossOrigin
@RestController
public class HealthCompetionTongjiBySchController extends YxyApiBaseController {
    @Value("${yx.rest.api.yx.path}")
    private String yxpath;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private YxyCompetitionStudentRepository yxyCompetitionStudentRepository;

    @RequestMapping(value = "/api_yw/home/activity/healthcompetition/huodongtongji/schooltongji", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespModel process(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel reqModel) {
        RespModel respModel = new RespModel();
        DecimalFormat df = new DecimalFormat("######0.00");
        // 该学校下总参与人数
        List<YxyCompetitionStudent> list = yxyCompetitionStudentRepository.findByStatusAndSchoolId(2,
                reqModel.schoolId);
        respModel.total = list.size();
        // 计算该学校下参与学生平均分
        TypedAggregation<YxyCompetitionStudent> totalavg = Aggregation.newAggregation(YxyCompetitionStudent.class,
                Aggregation.match(Criteria.where("status").is(2).and("schoolId").is(reqModel.schoolId)),
                Aggregation.group("schoolId").avg("score").as("avg"));
        AggregationResults<DateModel> resultZongtotal = mongoTemplate.aggregate(totalavg, DateModel.class);
        List<DateModel> dateModelLsttotal = resultZongtotal.getMappedResults();
        if (dateModelLsttotal.size() > 0) {
            respModel.avg = Double.valueOf(df.format(dateModelLsttotal.get(0).avg));
        }
        // 计算参与率
        try {
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
            Map<String, Object> formMap = new HashMap<String, Object>();
            formMap.put("stage", "全部");
            formMap.put("schoolId", reqModel.schoolId);
            HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(formMap, headers);
            SchRespModel httpResult = restTemplate.postForObject(yxpath + "/comm/stucount/schandstage", formEntity,
                    SchRespModel.class);
            Integer studentcount = httpResult.stucount;
            Double rate = 0.0d;
            if (studentcount != 0) {
                Double aLong = (double) list.size() / studentcount;
                rate = Double.valueOf(df.format(aLong * 100));
            }
            respModel.rate = rate;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return respModel;
    }

    // 远程调用接口,查询学校下小学初中高中共有多少学生
    protected static class SchRespModel extends YxyApiReqModel {
        // 学生总数
        public Integer stucount;
    }

    class DateModel {
        public Double avg;
    }

    protected static class ReqModel extends YxyApiReqModel {
        // 学校id
        public String schoolId;
    }

    protected static class RespModel extends YxyApiRespModel {
        // 总参与人数
        public Integer total;
        // 参与率
        public Double rate;
        // 平均分
        public Double avg;
    }
}
